<template>
  <div class="history-data">
    <div class="content-left">
      <div class="left-item">
        <div class="title-font">数据导入区</div>
        <div class="import-content">
          <el-button class="import-button" @click="getStlData" type="primary"
            >STL分解
          </el-button>
          <!-- <div class="btn-group">
            <el-button
              v-for="(item, index) in buttonList[0]"
              class="btn"
              type="primary"
              @click="btnClick(item)"
              >{{ item.name }}
            </el-button>
          </div> -->
        </div>
      </div>
      <div class="left-item">
        <div class="title-font">基于标准的重过载程度分析</div>
        <div style="margin: 6px">
          <div class="heavya-confirm-font">标准确定：</div>
          <div class="heavya-confirm-font">
            重载为：负载率为80%~100%，且持续两小时
          </div>
          <div class="heavya-confirm-font">
            过载为：负载率为100%~150%，且持续两小时
          </div>
        </div>
        <div class="import-content">
          <div style="display: flex; align-items: center; margin-bottom: 10px">
            <div>额定容量：</div>
            <el-input
              style="width: 50%"
              v-model="rated"
              placeholder="请输入额定容量"
            />
          </div>

          <el-button
            @click="getOverloadCompare"
            class="import-button"
            type="primary"
            >模型训练
          </el-button>
        </div>
      </div>
      <div class="left-item">
        <div class="title-font">基于正态分布确定阈值的重过载程度分析</div>
        <div style="margin: 6px">
          <div class="heavya-confirm-font">正态分布认为：</div>
          <div class="heavya-confirm-font">重载为：超出（0，μ+2σ）</div>
          <div class="heavya-confirm-font">过载为：超出（0，μ+2σ）</div>
        </div>
        <div class="import-content">
          <el-button
            @click="getNormalDistribution"
            class="import-button"
            type="primary"
            >模型训练
          </el-button>
        </div>
      </div>
      <div class="left-item">
        <div class="heavya-confirm-font">
          利用模糊理论对重过载状态进行评估，
        </div>
        <div class="heavya-confirm-font">
          得到多因素综合的重过载严重程度评估结果
        </div>
        <div class="import-content">
          <el-button
            class="import-button"
            @click="getOverloadJudge"
            type="primary"
            >重过载判据确定</el-button
          >
        </div>
      </div>
    </div>
    <div class="content-right">
      <!-- <div class="button-area">
        <el-button
          class="chart-button"
          type="primary"
          v-for="(item, index) in buttonList[1]"
          :key="item.type"
          @click="analysisClick(item)"
          >{{ item.name }}</el-button
        >
      </div>
      <div class="chart-content">
          <div class="chart-style">
            <Echarts
            v-if="chartData.xData.length > 0"
            :chartData="chartData"
            :chartId="'load'"
          ></Echarts>

          </div>
      </div> -->
      <div class="chart-content">
        <div class="charts">
          <div class="button-area">
            <div
              class="load-button"
              type="primary"
              v-if="analysisType == 'stl'"
              :class="btnType == item.type ? 'active' : ''"
              v-for="(item, index) in buttonList[0]"
              :key="item.type"
              @click="btnClick(item)"
            >
              {{ item.name }}
            </div>
            <div
              class="load-button"
              type="primary"
              v-if="analysisType && analysisType != 'stl'"
              :class="btnType == item.type ? 'active' : ''"
              v-for="(item, index) in buttonList[1]"
              :key="item.type"
              @click="analysisClick(item)"
            >
              {{ item.name }}
            </div>
          </div>
          <Echarts
            v-if="chartData.yData.length > 0 && !btnType.includes('ACF')"
            :chartData="chartData"
            :chartId="'STL'"
          ></Echarts>
          <acf-charts
            v-if="chartData.yData.length > 0 && btnType.includes('ACF')"
            :chartData="chartData"
            :chartId="'acf'"
          ></acf-charts>
        </div>
      </div>

      <div class="chart-content">
        <div class="table-font">结果展示</div>
        <ElTable
          style="height: 70%"
          :tableData="tableData"
          :tableColumns="tableColumns"
        ></ElTable>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import Echarts from "@/components/charts/echarts.vue";
import acfCharts from "./components/chart.vue";
import ElTable from "@/components/table.vue";
import {
  stlAnalysis,
  overloadCompare,
  normalDistribution,
} from "@/api/index.js";

const analysisType = ref(""); //分析类型

const buttonList = ref([
  [
    {
      // data_SR data_SS data_ST times_SR times_SS times_ST
      name: "趋势分量",
      type: "ST",
    },
    {
      name: "周期分量",
      type: "SS",
    },
    {
      name: "余项",
      type: "SR",
    },
    {
      name: "周期分量ACF图",
      type: "periodicACF",
    },
    {
      name: "余项ACF图",
      type: "remainderACF",
    },
  ],
  [
    {
      name: "月份重载分析",
      type: "monthHeavy",
    },
    {
      name: "星期重载分析",
      type: "weekHeavy",
    },
    {
      name: "月份过载分析",
      type: "monthLoad",
    },
    {
      name: "星期过载分析",
      type: "weekLoad",
    },
  ],
]);
const pageBtnList = ref([]);
const tableColumns = ref([]);
const tableData = ref([]);
const btnType = ref("ST");

//echarts图表数据
const chartData = ref({
  xData: [],
  yData: [],
  name: "",
});
const btnClick = (item) => {
  chartData.value.name = item.name;
  if (item.type == "periodicACF") {
    chartData.value.yData = stlData.value["SS_ACF"];
  } else if (item.type == "remainderACF") {
    chartData.value.yData = stlData.value["SR_ACF"];
  } else {
    chartData.value.xData = stlData.value["times_" + item.type];
    chartData.value.yData = stlData.value["data_" + item.type];
  }
  btnType.value = item.type;
};
const stlData = ref({});
const getStlData = () => {
  analysisType.value = "stl";
  stlAnalysis().then((res) => {
    if (res.code == 200) {
      delete res.code;
      stlData.value = res;
      dealTableData(res.outside);
      analysisType.value = "stl";
      pageBtnList.value = buttonList.value[0];
      btnClick({
        name: "趋势分量",
        type: "ST",
      });
    }
  });
};
//处理后台数据成前台展示的STLtable数据
const dealTableData = (dealData) => {
  tableColumns.value = [
    { prop: "name", label: "" },
    { prop: "max", label: "最大值" },
    { prop: "min", label: "最小值" },
    { prop: "mean", label: "平均值" },
  ];
  if (tableData.value.length > 0) {
    tableData.value = [];
  }
  let tableType = [
    {
      subStr: "row_means",
      name: "原始数据",
    },
    {
      subStr: "ST",
      name: "趋势分量",
    },
    {
      subStr: "SS",
      name: "周期分量",
    },
    {
      subStr: "SR",
      name: "余项",
    },
  ];
  tableType.map((item) => {
    let filteredEntries = Object.entries(dealData).filter(([key, value]) =>
      key.includes(item.subStr)
    );
    let tableItem = { name: item.name, max: "", min: "", mean: "" };
    filteredEntries.forEach((ele) => {
      if (item.subStr + "_max" == ele[0]) {
        tableItem.max = ele[1];
      }
      if (item.subStr + "_min" == ele[0]) {
        tableItem.min = ele[1];
      }
      if (item.subStr + "_mean" == ele[0]) {
        tableItem.mean = ele[1];
      }
    });
    tableData.value.push(tableItem);
  });
};
//基于标准的重过载程度分析
const overloadNormalData = ref({});
const rated = ref(0);
const getOverloadCompare = () => {
  analysisType.value = "overload";

  overloadCompare(rated.value).then((res) => {
    if (res.code == 200) {
      delete res.code;
      overloadNormalData.value = res;
      pageBtnList.value = buttonList.value[1];
      analysisType.value = "overload";
      analysisClick({
        name: "月份重载分析",
        type: "monthHeavy",
      });
    }
  });
};
//基于正态分布确定阈值的重过载程度分析
const getNormalDistribution = () => {
  analysisType.value = "normal";

  normalDistribution().then((res) => {
    if (res.code == 200) {
      delete res.code;
      overloadNormalData.value = res;
      pageBtnList.value = buttonList.value[1];
      analysisType.value = "normal";
      analysisClick({
        name: "月份重载分析",
        type: "monthHeavy",
      });
    }
  });
};

const analysisClick = (item) => {
  chartData.value.name = item.name;
  let tableParams = {
    type: "",
    data: {
      times: "", //次数
      time: "", //时间
    },
    dataLength: "",
  };
  if (item.type.includes("month")) {
    chartData.value.xData = overloadNormalData.value["time_monthly"];
    tableParams.type = "month";
    tableParams.data.time = overloadNormalData.value["time_monthly"];
    if (item.type.includes("Heavy")) {
      tableParams.data.times = overloadNormalData.value["monthly_Count_heavy"];
      chartData.value.yData = overloadNormalData.value["monthly_Count_heavy"];
    } else {
      chartData.value.yData =
        overloadNormalData.value["monthly_Count_overload"];
      tableParams.data.times =
        overloadNormalData.value["monthly_Count_overload"];
    }
  }
  if (item.type.includes("week")) {
    chartData.value.xData = overloadNormalData.value["time_week"];
    tableParams.type = "week";
    tableParams.data.time = overloadNormalData.value["time_week"];
    if (item.type.includes("Heavy")) {
      chartData.value.yData = overloadNormalData.value["week_Count_heavy"];
      tableParams.data.times = overloadNormalData.value["week_Count_heavy"];
    } else {
      chartData.value.yData = overloadNormalData.value["week_Count_overload"];
      tableParams.data.times = overloadNormalData.value["week_Count_overload"];
    }
  }
  btnType.value = item.type;

  detailTableData(
    tableParams.type,
    tableParams.data,
    tableParams.data.time.length
  );
};

const detailTableData = (type, data, dataLength) => {
  // 检查 data 参数是否包含必要的属性
  if (!data || !data.times || !data.time) {
    console.error("Invalid data object provided");
    return;
  }

  // 定义一个映射关系，避免重复代码
  const typeMapping = {
    month: { prop: "month", label: "月份" },
    week: { prop: "week", label: "日期" },
  };

  // 如果传入的 type 无效，直接返回
  const columnConfig = typeMapping[type];
  if (!columnConfig) {
    console.error("Invalid type provided");
    return;
  }

  // 设置表格列
  tableColumns.value = [
    { prop: columnConfig.prop, label: columnConfig.label },
    { prop: "times", label: `${columnConfig.label}次数` },
  ];

  // 使用 map 生成表格数据
  tableData.value = Array.from({ length: dataLength }, (_, index) => ({
    [columnConfig.prop]: data.time[index],
    times: data.times[index],
  }));
};
const getOverloadJudge = () => {
  tableColumns.value = [
    { prop: "value", label: "评价值" },
    { prop: "status", label: "变压器状态" },
  ];
  tableData.value = [
    {
      value: "0~0.72",
      status: "正常",
    },
    {
      value: "0.72~0.9",
      status: "重载",
    },
    {
      value: "0.9~1.5",
      status: "过载",
    },
  ];
};

onMounted(() => {
  console.log("Component mounted");
});
</script>
<style lang="scss" scoped>
@import "@/global.scss";
@import "@/common/table.scss";
.history-data {
  width: 100%;
  height: 100%;
  display: flex;
  .content-left {
    // flex: 1;
    width: vw(400);
    overflow: hidden;
    height: 100%;
    display: flex;
    flex-direction: column;
    border-left: 1px solid #818181;

    .left-item {
      width: 100%;
      flex: 1;
      box-sizing: border-box;
      padding: 20px;
      border-bottom: 1px solid #818181;
      border-right: 1px solid #818181;
      .import-content {
        width: 100%;
        margin: 10px;
        text-align: center;
      }
      .import-button {
        width: vw(240);
      }
    }
    .left-item:last-child {
      border-bottom: 0;
    }
    .btn-group {
      display: flex;
      width: 100%;
      justify-content: center;
      flex-wrap: wrap;
      .btn {
        margin-right: 10px;
        margin-top: 10px;
      }
    }
    .title-font {
      font-size: 20px;
      color: #fff;
      font-weight: 500;
      font-family: Georgia, "Times New Roman", Times, serif;
    }
    .heavya-confirm-font {
      font-size: 15px;
      color: #fff;
      font-weight: 500;
      font-family: Georgia, "Times New Roman", Times, serif;
    }
    .model-font {
      font-size: 20px;
      color: #fff;
      font-weight: 500;
      font-family: Georgia, "Times New Roman", Times, serif;
      margin-bottom: 20px;
    }
  }
  .content-right {
    // flex: 3.5;
    width: calc(100% - vw(400));
    overflow: hidden;
    height: 100%;
    border-right: 1px solid #818181;
    .button-area {
      width: auto;
      height: calc(100% - vh(100));
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      box-sizing: border-box;
      gap: vh(10);
    }
    .chart-content {
      width: 100%;
      height: calc(100vh / 2);
      border-top: 1px solid #818181;
      padding: vh(10) vw(20);
      box-sizing: border-box;
    }
    .load-button {
      min-width: vw(100);
      padding: vw(10);
      font-size: 14px;
      border-radius: 4px;
      text-align: center;
      cursor: pointer;
      background-color: #ecf5ff;
      color: #409eff;
      &:hover {
        background-color: #409eff;
        color: #ecf5ff;
      }
    }
    // .load-button:hover {

    // }
    .active {
      background-color: #409eff;
      color: #ecf5ff;
    }

    .choose-date {
      display: flex;
      align-items: center;
      gap: vw(10);
    }
    .chart-style {
      width: 100%;
      height: 100%;
    }
    .charts {
      width: 100%;
      display: flex;
      height: 100%;
      overflow: hidden;
    }
    .table-font {
      color: aqua;
      font-size: 16px;
      margin-bottom: 14px;
    }
  }
}
:deep(.el-form-item__label) {
  color: #fff;
  font-size: 15px;
}
</style>
